package org.zn.mvcbase.mybatis.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.util.StringUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 崔超
 * @date 2017年11月21日
 * @description list集合转换String
 * @version 1.00 beta
 */
@MappedTypes(value= {List.class})
@MappedJdbcTypes(value={JdbcType.VARCHAR})
public class List2String extends BaseTypeHandler<List<String>> {
	
	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType)throws SQLException {
		String string = String.join(",", parameter);
		ps.setString(i, string);
	}

	@Override
	public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
		String string = rs.getString(columnName);
		return string2List(string);
	}

	@Override
	public List<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		String string = rs.getString(columnIndex);
		return string2List(string);
	}

	@Override
	public List<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		String string = cs.getString(columnIndex);
		return  string2List(string);

	}

	private List<String> string2List(String string){
		List<String> list = new ArrayList<String>();
		if(StringUtils.isEmpty(string)){
			return list;
		}
		String[] array = string.split(",");
		list.addAll(Arrays.asList(array));
		return list;
	}
	

}
